package com.demo.freemarker.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import com.demo.freemarker.vo.BaseVo;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkUtil {
	
    //你模板放置的路径
    // 创建Configuration实例
    private static Configuration cfg = new Configuration();

    public static void genateCode(BaseVo baseVo, String sql) {
        Template temp = null;
        File loadTemplateFile = new File(baseVo.getTemplatepath());
        try {
            cfg.setDirectoryForTemplateLoading(loadTemplateFile);
            String saveDir = baseVo.getSavedir();

            Map<String, Map<String, Params>> classPropties = ConnectMySql
                    .connect(baseVo, sql);
            SetJavaCode(temp, baseVo.getModelpath(), saveDir, classPropties);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 首字母大写
    public static String toUpString(String className) {
        char[] cs = className.toCharArray();
        cs[0] -= 32;
        String ClassName = String.valueOf(cs);
        return ClassName;
    }

    @SuppressWarnings("unused")
	public static void SetJavaCode(Template temp,String packagePath, String saveDir,
            Map<String, Map<String, Params>> classPropties) {

        Map<String, Params> m = classPropties.get("Paramss");
        /*
         * 每一个实例里面都存有tableName，这里取第0个拿tableName
         */
        String tableName = (String) (m.get("Params0").getTableName());
        /*
         * 表明为m_user,指定类名为User
         */
        String className = tableName.replaceAll("_", "");
        /*
         *  使首字母大写
         */
        String ClassName = toUpString(className);
        /*
         *  存入，作为参数给页面 className：作为引用名 ClassName：作为类名
         */
        String fileNameEntityPath = saveDir 
            + "/entity/" + tableName + ".txt";
        File newsDir = new File(saveDir);
        File newsDirEntity = new File(saveDir + "/entity/");
        boolean flag = false;
	    flag = (Boolean) (newsDir.exists() == false ? newsDir.mkdirs() : true);
	    flag = (Boolean) (newsDirEntity.exists() == false ? newsDirEntity.mkdirs() : true);

        try (
                Writer outEntity = new OutputStreamWriter(new FileOutputStream(
                        fileNameEntityPath), "utf-8");) {

        	 Map<String,Object> tmap = new HashMap<String, Object>();
             tmap.put("model", classPropties);
             
            
            /*
             * Entity生成
             */
            temp = cfg.getTemplate("cona.ftl");
            packagePath = packagePath + "." + newsDirEntity.getName();
            tmap.put("package", packagePath);
            temp.process(tmap, outEntity);
            System.out.println("------------Entity生成完毕-------------");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
    	
    	String driver = "oracle.jdbc.driver.OracleDriver";
    	String url = "jdbc:oracle:thin:@192.168.100.47:1521:ZXBANK";
        String username = "mps";
        String password = "mps12345";
        String table = "'REWARD_TICKET_INFO'".toUpperCase();
        
        
      /*  String sql = "SELECT T1.TABLE_NAME as table_name," + 
        		"T1.COLUMN_NAME as column_name," + 
        		"T2.COMMENTS as column_comment," + 
        		"T1.DATA_TYPE || '(' || T1.DATA_LENGTH || ')' as column_type," + 
        		"T1.NULLABLE as column_default" + 
        		" FROM USER_TAB_COLS T1, USER_COL_COMMENTS T2" + 
        		" WHERE T1.TABLE_NAME = T2.TABLE_NAME" + 
        		" AND T1.COLUMN_NAME = T2.COLUMN_NAME" + 
        		" AND T1.TABLE_NAME = " + table;*/
        
        
        String sql1 = "SELECT T.*, P.POSITION as pkey FROM " + 
        		"(SELECT T1.TABLE_NAME AS TABLE_NAME," + 
        		"T1.COLUMN_NAME AS COLUMN_NAME," + 
        		"T2.COMMENTS AS COLUMN_COMMENT," + 
        		"T1.DATA_TYPE || '(' || CASE" + 
        		" WHEN T1.DATA_TYPE = 'NUMBER' and T1.DATA_SCALE = '0' THEN" + 
        		" T1.DATA_PRECISION || ''" + 
        		" WHEN T1.DATA_TYPE = 'NUMBER' and T1.DATA_SCALE != '0' THEN" + 
        		" T1.DATA_PRECISION || ',' || T1.DATA_SCALE" + 
        		" ELSE" + 
        		" T1.DATA_LENGTH || ''" + 
        		" END || ')' AS COLUMN_TYPE," + 
        		"T1.NULLABLE AS COLUMN_DEFAULT" + 
        		" FROM USER_TAB_COLS T1, USER_COL_COMMENTS T2" + 
        		" WHERE T1.TABLE_NAME = T2.TABLE_NAME" + 
        		"   AND T1.COLUMN_NAME = T2.COLUMN_NAME" + 
        		"   AND T1.TABLE_NAME = "+ table +
        		") T LEFT JOIN (SELECT CU.*" + 
        		"  FROM USER_CONS_COLUMNS CU, USER_CONSTRAINTS AU" + 
        		" WHERE CU.CONSTRAINT_NAME = AU.CONSTRAINT_NAME" + 
        		"   AND AU.CONSTRAINT_TYPE = 'P'" + 
        		"   AND AU.TABLE_NAME = "+ table +
        		") P ON T.COLUMN_NAME = P.COLUMN_NAME";
        
    	BaseVo vo = new BaseVo();
    	vo.setDriver(driver);
    	vo.setUrl(url);
    	vo.setUsername(username);
    	vo.setPassword(password);
    	vo.setModelpath("com.demo.freemarker.test");

    	vo.setSavedir("D:\\WorkSpace\\eclipse-workspace\\FreemarkerDemo\\Freemarker\\src\\main\\java\\com\\demo\\freemarker\\test");
    	vo.setTemplatepath("D:\\WorkSpace\\eclipse-workspace\\FreemarkerDemo\\Freemarker\\src\\main\\java\\com\\demo\\freemarker\\model");
        genateCode(vo, sql1);
    }

}
